package com.utcook.host.fragmentdialog

import android.os.Bundle
import android.os.CountDownTimer
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.utcook.host.fragmentdialog.databinding.FragmentRecipeCookingBinding

class RecipeCookingFragment : Fragment() {

    private var _binding: FragmentRecipeCookingBinding? = null
    private val binding get() = _binding!!
    private var burnerViewModel: BurnerViewModel? = null
    private var recipe: Recipe? = null
    private var burnerIndex: Int = 0
    private var isCookingCompleted = false
    private var updateTimer: android.os.Handler? = null
    private var stepAdapter: CookingStepAdapter? = null

    companion object {
        fun newInstance(viewModel: BurnerViewModel, recipe: Recipe, burnerIndex: Int): RecipeCookingFragment {
            val fragment = RecipeCookingFragment()
            fragment.burnerViewModel = viewModel
            fragment.recipe = recipe
            fragment.burnerIndex = burnerIndex
            android.util.Log.d("RecipeCookingFragment", "newInstance: 创建炉头${burnerIndex + 1}的烹饪Fragment, burnerIndex=$burnerIndex")
            return fragment
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentRecipeCookingBinding.inflate(inflater, container, false)
        binding.fragment = this
        binding.recipe = recipe
        
        setupCookingView()
        setupCookingSteps()
        setupCookingTimer()
        
        return binding.root
    }

    private fun setupCookingView() {
        recipe?.let { recipe ->
            binding.tvRecipeName.text = recipe.name
            binding.tvRecipeDuration.text = "烹饪时间: ${recipe.duration}分钟"
            binding.tvRecipeDifficulty.text = "难度: ${recipe.difficulty}"
            binding.tvRecipeDescription.text = recipe.description
            binding.tvBurnerInfo.text = "炉头${burnerIndex + 1}"
            
            // 设置倒计时初始值（10秒）
            binding.tvCountdown.text = "10"
        }
    }
    
    private fun setupCookingSteps() {
        recipe?.let { recipe ->
            if (recipe.steps.isNotEmpty()) {
                val layoutManager = androidx.recyclerview.widget.LinearLayoutManager(context)
                binding.rvCookingSteps.layoutManager = layoutManager
                
                // 获取当前步骤索引和剩余时间
                val currentStepIndex = burnerViewModel?.getBurnerCookingState(burnerIndex)?.currentStepIndex ?: 0
                val currentStepRemainingSeconds = burnerViewModel?.getBurnerCookingState(burnerIndex)?.currentStepRemainingSeconds ?: 0
                
                // 创建适配器
                stepAdapter = CookingStepAdapter(recipe.steps, currentStepIndex, currentStepRemainingSeconds)
                binding.rvCookingSteps.adapter = stepAdapter
            }
        }
    }

    fun setupCookingTimer() {
        // 使用BurnerViewModel中的倒计时数据
        burnerViewModel?.let { viewModel ->
            val cookingState = viewModel.getBurnerCookingState(burnerIndex)
            cookingState?.let { state ->
                android.util.Log.d("RecipeCookingFragment", "setupCookingTimer: 炉头${burnerIndex + 1}, burnerIndex=$burnerIndex, isCooking=${state.isCooking}, isCompleted=${state.isCompleted}")
                
                // 根据ViewModel状态设置Fragment状态
                if (state.isCompleted) {
                    showCookingCompleted()
                } else if (state.isCooking) {
                    // 如果正在烹饪，显示烹饪页面
                    binding.cookingView.visibility = View.VISIBLE
                    binding.completedView.visibility = View.GONE
                    isCookingCompleted = false
                    updateCountdownDisplay(state.remainingSeconds)
                    updateCookingSteps(state.currentStepIndex)
                    updatePauseButtonState(state.isPaused)
                } else {
                    // 如果状态已重置，显示初始状态
                    binding.cookingView.visibility = View.VISIBLE
                    binding.completedView.visibility = View.GONE
                    isCookingCompleted = false
                    binding.tvCountdown.text = "10"
                    updateCookingSteps(0)
                    updatePauseButtonState(false)
                }
            }
        }
        
        // 启动定时器，每秒更新倒计时显示
        startUpdateTimer()
    }
    
    override fun onResume() {
        super.onResume()
        android.util.Log.d("RecipeCookingFragment", "onResume: 炉头${burnerIndex + 1}")
        // 当Fragment重新显示时，重新设置状态
        setupCookingTimer()
    }
    
    private fun startUpdateTimer() {
        updateTimer?.removeCallbacksAndMessages(null)
        updateTimer = android.os.Handler(android.os.Looper.getMainLooper())
        
        val updateRunnable = object : Runnable {
            override fun run() {
                burnerViewModel?.let { viewModel ->
                    val cookingState = viewModel.getBurnerCookingState(burnerIndex)
                    cookingState?.let { state ->
                        if (state.isCooking) {
                            updateCountdownDisplay(state.remainingSeconds)
                            if (!state.isPaused) {
                                updateCookingSteps(state.currentStepIndex)
                            }
                            updatePauseButtonState(state.isPaused)
                            updateTimer?.postDelayed(this, 1000)
                        } else if (state.isCompleted && !isCookingCompleted) {
                            showCookingCompleted()
                        }
                    }
                }
            }
        }
        
        updateTimer?.post(updateRunnable)
    }
    
    private fun updateCountdownDisplay(seconds: Int) {
        binding.tvCountdown.text = seconds.toString()
    }
    
    private fun updateCookingSteps(currentStepIndex: Int) {
        recipe?.let { recipe ->
            if (recipe.steps.isNotEmpty()) {
                // 获取当前步骤的剩余时间
                val currentStepRemainingSeconds = burnerViewModel?.getBurnerCookingState(burnerIndex)?.currentStepRemainingSeconds ?: 0
                
                // 如果适配器已存在，直接更新数据
                if (stepAdapter != null) {
                    stepAdapter?.updateCurrentStep(currentStepIndex, currentStepRemainingSeconds)
                } else {
                    // 首次创建适配器
                    stepAdapter = CookingStepAdapter(recipe.steps, currentStepIndex, currentStepRemainingSeconds)
                    binding.rvCookingSteps.adapter = stepAdapter
                }
                
                // 只在步骤切换时滚动到当前步骤
                val layoutManager = binding.rvCookingSteps.layoutManager as? androidx.recyclerview.widget.LinearLayoutManager
                val firstVisiblePosition = layoutManager?.findFirstVisibleItemPosition() ?: 0
                val lastVisiblePosition = layoutManager?.findLastVisibleItemPosition() ?: 0
                
                // 如果当前步骤不在可见范围内，才滚动
                if (currentStepIndex < firstVisiblePosition || currentStepIndex > lastVisiblePosition) {
                    binding.rvCookingSteps.post {
                        binding.rvCookingSteps.smoothScrollToPosition(currentStepIndex)
                    }
                }
            }
        }
    }
    
    private fun updatePauseButtonState(isPaused: Boolean) {
        val pauseButton = binding.btnPauseResume
        if (isPaused) {
            pauseButton.setImageResource(android.R.drawable.ic_media_play)
            pauseButton.contentDescription = "恢复"
        } else {
            pauseButton.setImageResource(android.R.drawable.ic_media_pause)
            pauseButton.contentDescription = "暂停"
        }
    }
    
    fun onPauseResumeClick() {
        burnerViewModel?.let { viewModel ->
            viewModel.togglePauseCookingOnBurner(burnerIndex)
            // 更新按钮状态
            val cookingState = viewModel.getBurnerCookingState(burnerIndex)
            cookingState?.let { state ->
                updatePauseButtonState(state.isPaused)
            }
        }
    }
    
    fun onStopClick() {
        burnerViewModel?.let { viewModel ->
            viewModel.stopCookingOnBurner(burnerIndex)
            // 返回菜谱操作页面
            onBackToRecipeList()
        }
    }

    private fun showCookingCompleted() {
        isCookingCompleted = true
        binding.cookingView.visibility = View.GONE
        binding.completedView.visibility = View.VISIBLE
        
        recipe?.let { recipe ->
            binding.tvCompletedRecipeName.text = recipe.name
        }
    }
    
    fun resetCookingState() {
        isCookingCompleted = false
        
        // 重置UI状态
        binding.cookingView.visibility = View.VISIBLE
        binding.completedView.visibility = View.GONE
        binding.tvCountdown.text = "10"
        
        // 重新启动更新定时器
        startUpdateTimer()
        
        android.util.Log.d("RecipeCookingFragment", "烹饪状态已重置")
    }

    fun onBackToRecipeList() {
        // 返回菜谱操作页面
        android.util.Log.d("RecipeCookingFragment", "返回菜谱列表被点击")
        
        // 重置当前炉头的烹饪状态
        burnerViewModel?.resetBurnerCookingState(burnerIndex)
        
        // 通知父Fragment隐藏当前烹饪页面，显示菜谱操作页面
        (parentFragment as? RecipeFragment)?.showRecipeOperation()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        updateTimer?.removeCallbacksAndMessages(null)
        updateTimer = null
        _binding = null
    }
}